//
//  FPRootViewController.m
//  FilmParadise
//
//  Created by lanou3g on 15/7/14.
//  Copyright (c) 2015年 DLYgroup. All rights reserved.
//

#import "FPRootViewController.h"
#import "FPMovieViewController.h"
#import "FPCinemaViewController.h"
#import "FPLocation.h"
#import "FPMovieHotPlayModel.h"
#import "FPPredictVidio.h"
#import "FPHotPlayModel.h"
#import "FPWillPlayModel.h"
#import "FPCinemaModel.h"
#import "FPMapViewController.h"
#import "FPMapViewController.h"
#define kHotPlayUrl @"http://api.m.mtime.cn/PageSubArea/HotPlayMovies.api?locationId=%@"
#define kWillPlayUrl @"http://api.m.mtime.cn/Movie/MovieComingNew.api?locationId=%@"
#define kCinemaUrl @"http://api.m.mtime.cn/OnlineLocationCinema/OnlineCinemasByCity.api?locationId=%@"

@interface FPRootViewController ()<UISearchResultsUpdating,UISearchControllerDelegate>

@property (nonatomic, strong) FPMovieViewController  * fpMovieVC;
@property (nonatomic, strong) FPCinemaViewController * fpCinemaVC;
@property (nonatomic, strong) FPMapViewController    * fpMapVC;
@property (nonatomic, strong) MBProgressHUD          * HUD;

@property (nonatomic, strong) NSMutableArray * movieArray;
@property (nonatomic, strong) NSMutableArray * hotPlayArray;
@property (nonatomic, strong) NSMutableArray * willTopArray;// 传给轮播图信息
@property (nonatomic, strong) NSMutableArray * willPlayArray;// 传给tableView信息
@property (nonatomic, strong) NSMutableArray * predicVideoArray;
@property (nonatomic, strong) NSMutableArray * cinemaArray;// 影院信息数组
@property (nonatomic, strong) NSMutableArray * featureArray;// 影院信息中feature的内容
@property (nonatomic, strong) UISearchController * searchController;
@property (nonatomic, strong) NSMutableArray * distanceArray;
@property (nonatomic, strong) NSMutableArray * cinemaNameArray;
@end

@implementation FPRootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController.navigationBar setBackgroundColor:[UIColor cyanColor]];
    // Do any additional setup after loading the view.
    
    // 请求网络数据
    [self setUrl];
    
    // 创建子视图
    [self B_SubController];
    
    // 创建barbutton
    [self B_barButton];
    
    // 创建segmentcontroller
    [self B_segmentController];
    if (self.isMainWillShow == YES) {
        [self.fpMovieVC titleButton2Action];
    }
    if (self.isMainFindMovie == YES) {
        [self segment:1];
    }
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"cgClear"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.101 green:0.196 blue:1.000 alpha:1.000];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setBackgroundColor:[UIColor blueColor]];
    UIView *statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth , 20)];
    statusBarView.backgroundColor = [UIColor blueColor];
    [self.view addSubview:statusBarView];

}

/*=========================================解析网络数据=============================================*/
#pragma mark - 解析网络数据
- (void)setUrl
{
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.view bringSubviewToFront:_HUD];
    if ([[FPNetWork shareInstance] rechability]) {
        self.HUD.labelText = @"正在加载";
        [self S_analysisHotPlay];
        [self S_analysisWillPlay];
        [self T_analysisCinema];
    }
    else
    {
        self.HUD.labelText = @"请检查网络";
    }
    
}
#pragma mark - 解析电影界面数据
// 解析正在热映界面数据
- (void)S_analysisHotPlay
{
    
    // 初始化数组
    self.movieArray              = [NSMutableArray array];
    self.hotPlayArray            = [NSMutableArray array];
    self.fpMovieVC.moviewArray   = [NSMutableArray array];
    self.fpMovieVC.hotMovieArray = [NSMutableArray array];
    
    // 创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:kHotPlayUrl,[FPLocation shareInstance].locationID]]
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
    NSLog(@"--------------%@",[NSString stringWithFormat:kHotPlayUrl,[FPLocation shareInstance].locationID]);
    
    // 开启异步连接
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                               if (data == nil) return;
                               NSMutableDictionary *hotDic  = [NSJSONSerialization JSONObjectWithData:data
                                                                                              options:NSJSONReadingMutableContainers error:nil];
                               FPHotPlayModel * model       = [FPHotPlayModel MovieHotPlayWithDictionary:hotDic];
                               [self.movieArray addObject:model];
                               self.fpMovieVC.moviewArray   = self.movieArray;//----->外面大model
                               NSArray *array               = [hotDic objectForKey:@"movies"];
                               for (NSDictionary *dic in array) {
                                   FPMovieHotPlayModel * hotModel = [FPMovieHotPlayModel MovieHotPlayWithDictionary:dic];
                                   NSDictionary * nearestDic = [dic objectForKey:@"nearestShowtime"];
                                   hotModel.isTicket               = (BOOL)nearestDic[@"isTicket"];
                                   hotModel.nearestCinemaCount     = (int)nearestDic[@"nearestCinemaCount"];
                                   hotModel.nearestShowDay         = (int)nearestDic[@"nearestShowDay"];
                                   hotModel.nearestShowtimeCount   = (int)nearestDic[@"nearestShowtimeCount"];
                                   [self.hotPlayArray addObject:hotModel];
                                   self.fpMovieVC.hotMovieArray = self.hotPlayArray;//----->里面小model
                               }
                               [_fpMovieVC.hotTableView reloadData];
                               [self.HUD hide:YES afterDelay:1];
                           }];
}

// 解析即将上映界面数据
- (void)S_analysisWillPlay
{
    // 创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:kWillPlayUrl,[FPLocation shareInstance].locationID]]
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
    // 开启异步连接
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                               
                               // 初始化数组
                               self.willTopArray             = [NSMutableArray array];// 存放顶部信息数组
                               self.willPlayArray            = [NSMutableArray array];// 存放即将上映数组
                               self.predicVideoArray         = [NSMutableArray array];// 存放即将上映预告片
                               self.fpMovieVC.willPlayArray  = [NSMutableArray array];// 传值给fpMovie界面
                               self.fpMovieVC.willTopArray   = [NSMutableArray array];// 传值给fpMovie界面
                               self.fpMovieVC.videoArray     = [NSMutableArray array];// 传值给fpTrailer界面
                               
                               if (data == nil) return;
                               // 得到最外层大字典
                               NSMutableDictionary *willDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                               // 获得字典里面的数组
                               NSArray *attentionArray          = [willDic objectForKey:@"attention"];
                               // 遍历数组获取里面的数据(字典形式存放)
                               [attentionArray enumerateObjectsUsingBlock:^(NSDictionary *dic, NSUInteger idx, BOOL *stop) {
                                   FPWillPlayModel *model       = [FPWillPlayModel willPlayModelWithDictionary:dic];
                                   model.ID                     = (NSInteger)[dic objectForKey:@"id"];
                                   [self.willTopArray addObject:model];
                               }];
                               self.fpMovieVC.willTopArray      = self.willTopArray;
                               
                               // 获得字典里面的数组
                               NSArray *moviecomingsArray       = [willDic objectForKey:@"moviecomings"];
                               // 遍历数组获取里面的数组
                               [moviecomingsArray enumerateObjectsUsingBlock:^(NSDictionary * dic, NSUInteger idx, BOOL *stop) {
                                   FPWillPlayModel *model       = [FPWillPlayModel willPlayModelWithDictionary:dic];
                                   [self.willPlayArray addObject:model];
                               }];
                               self.fpMovieVC.willPlayArray     = self.willPlayArray;
                               // 刷新视图;
                               [self.fpMovieVC.WillTableView reloadData];
                               [self.fpMovieVC.topTableView reloadData];
                               [_fpCinemaVC.collectionView reloadData];
                               [_fpCinemaVC.tableView reloadData];
                               
                               [self.HUD hide:YES afterDelay:1];
                               
                           }];
    
    
}

// 解析影院界面数据
- (void)T_analysisCinema
{
    
    // 初始化数组
    self.cinemaArray                = [NSMutableArray array];// 存放cinema界面影片信息
    self.featureArray               = [NSMutableArray array];// 存放cinema界面feature中的信息
    self.distanceArray              = [NSMutableArray array];// 存放cinema界面距离的数组
    self.cinemaNameArray            = [NSMutableArray array];// 存放cinema界面影院名称的数组
    self.fpCinemaVC.cinemaArray     = [NSMutableArray array];// 传值给cinema界面
    self.fpCinemaVC.featureArray    = [NSMutableArray array];// 传值给cinema界面
    //    self.fpCinemaVC.cinemaNameArray = [NSMutableArray array];// 传值给cinema界面
    //    self.fpCinemaVC.distanceArray   = [NSMutableArray array];// 传值给cinema界面
    //    self.fpMapVC.cinemaNameArray    = [NSMutableArray array];
    //[FPLocation shareInstance].locationID
    //@"292"
    // 创建网络请求
    [LORequestManger GET:[NSString stringWithFormat:kCinemaUrl,[FPLocation shareInstance].locationID]
                 success:^(id response) {
                     NSArray *array = (NSArray *)response;
                     [array enumerateObjectsUsingBlock:^(NSDictionary *dic, NSUInteger idx, BOOL *stop) {
                         FPCinemaModel *model = [FPCinemaModel cinemaModelWithDictionary:dic];
                         [self.cinemaArray addObject:model];
                         // 百度定位
//                         BMKMapPoint point1 = BMKMapPointForCoordinate(CLLocationCoordinate2DMake([FPLocation shareInstance].FPlatitude, [FPLocation shareInstance].FPlongitude));
//                         BMKMapPoint point2 = BMKMapPointForCoordinate(CLLocationCoordinate2DMake(model.latitude, model.longitude));
//                         CLLocationDistance distance = BMKMetersBetweenMapPoints(point1, point2);
                         // 系统自带定位
                         CLLocation *current = [[CLLocation alloc] initWithLatitude:[FPLocation shareInstance].FPlatitude longitude:[FPLocation shareInstance].FPlongitude];
                         CLLocation *cinemaPlace = [[CLLocation alloc] initWithLatitude:model.latitude longitude:model.longitude];
                         CLLocationDistance distance = [current distanceFromLocation:cinemaPlace];
                         model.distance     = [NSString stringWithFormat:@"%.1f",distance/1000];
                         [self.distanceArray addObject:model.distance];
                         [self.cinemaNameArray addObject:model.cinameName];
                         NSDictionary *featureDic    = [dic objectForKey:@"feature"];
                         FPCinemaModel *featureModel = [FPCinemaModel cinemaModelWithDictionary:featureDic];
                         [self.featureArray addObject:featureModel];
                     }];
                     self.fpCinemaVC.cinemaArray     = _cinemaArray;
                     self.fpCinemaVC.featureArray    = _featureArray;
                     // 刷新数据
                     [self.fpCinemaVC.tableView reloadData];
                     [self.fpCinemaVC.collectionView reloadData];
                 } failure:nil];
}

/*=========================================创建视图=============================================*/
#pragma mark - 创建视图
// 创建子视图
- (void)B_SubController
{
    self.fpCinemaVC = [[FPCinemaViewController alloc] init];
    self.fpCinemaVC.view.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64);
    
    [self addChildViewController:_fpCinemaVC];
    [self.view addSubview:_fpCinemaVC.view];
    
    self.fpMovieVC = [[FPMovieViewController alloc] init];
    self.fpMovieVC.view.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64);
    [self addChildViewController:_fpMovieVC];
    [self.view addSubview:_fpMovieVC.view];
    
    
    
}


// 添加uibarbuttonitem
- (void)B_barButton
{
    // 添加左上角barbutton
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithTitle:[FPLocation shareInstance].cityLocal style:UIBarButtonItemStyleDone target:self action:@selector(leftButtonAction:)];
    self.navigationItem.leftBarButtonItem = leftButton;
    
    // 添加右上角button
    UIBarButtonItem * rightButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(rightButtonAction)];
    self.navigationItem.rightBarButtonItem = rightButton;
    
    
    
}

- (void)rightButtonAction
{
    
}

// 在titlebar上创建segment
- (void)B_segmentController
{
    NSArray *titleArray = @[@"电影",@"影院"];//字面量创建数组存放segment标题
    UISegmentedControl * segment = [[UISegmentedControl alloc] initWithItems:titleArray];
    segment.frame = CGRectMake(0, 0, 200, 30);
    segment.layer.cornerRadius = 15;
    segment.layer.masksToBounds = YES;
    segment.layer.borderColor = [UIColor whiteColor].CGColor;
    segment.layer.borderWidth = 2.0;
    segment.selectedSegmentIndex = 0;
    if (self.isMainFindMovie == YES) {
        segment.selectedSegmentIndex = 1;
    }
    //    segment.momentary = YES;
    [segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = segment;
    //    [self segmentAction:segment];
}
/*=========================================方法实现=============================================*/
#pragma mark - 方法实现
// 点击进图地点
- (void)leftButtonAction:(UIBarButtonItem *)setter
{
    NSLog(@"点击进入城市选择地图");
//    _fpMapVC = [[FPMapViewController alloc] init];
    //    [self.navigationController pushViewController:_fpMapVC animated:YES];
//    [self presentViewController:_fpMapVC animated:YES completion:nil];
}


// segment切换视图点击事件
- (void)segmentAction:(UISegmentedControl *)segment
{
    NSInteger index = segment.selectedSegmentIndex;
    [self segment:index];
}

- (void)segment:(NSInteger)index
{
    if (index == 0) {
        NSLog(@"切换到电影视图");
        
        
        [UIView transitionFromView:_fpCinemaVC.view toView:_fpMovieVC.view duration:0.2 options:UIViewAnimationOptionTransitionNone completion:nil];
        
        
    }else{
        NSLog(@"切换到影院视图");
        [UIView transitionFromView:_fpMovieVC.view toView:_fpCinemaVC.view duration:0.2 options:UIViewAnimationOptionTransitionNone completion:nil];
        
        
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
